package org.oxenframework.common.utils;

import java.io.Serializable;
import java.util.Arrays;

/**
 *
 */
public class ByteArrayFile implements OxenFile, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7998740537989546457L;

	public static final String IMAGE_TYPE_JPG = "JPG";

	public static final String IMAGE_TYPE_JPEG = "JPEG";

	public static final String IMAGE_TYPE_PNG = "PNG";

	public static final String IMAGE_TYPE_GIF = "GIF";

	private static final String[] FILE_EXTS = { IMAGE_TYPE_JPG, IMAGE_TYPE_JPEG, IMAGE_TYPE_PNG, IMAGE_TYPE_GIF };

	private static final byte[][] FILE_MAGS = new byte[][] { new byte[] { (byte) 0xFF, (byte) 0xD8, (byte) 0xFF, (byte) 0xE0 }, // JPG
			new byte[] { (byte) 0xFF, (byte) 0xD8, (byte) 0xFF, (byte) 0xE1 }, // JPEG
			new byte[] { (byte) 0x89, (byte) 0x50, (byte) 0x4E, (byte) 0x47 }, // PNG
			new byte[] { (byte) 0x47, (byte) 0x49, (byte) 0x46, (byte) 0x38 } // GIF
	};

	private String fileType;

	private byte[] fileData;

	public ByteArrayFile() {
	}

	public ByteArrayFile(byte[] fileData) {
		this.fileData = fileData;
		this.fileType = getFileFormat(fileData);
	}

	public void setImageData(byte[] fileData) {
		this.fileData = fileData;
		this.fileType = getFileFormat(fileData);
	}

	/**
	 * 判断真的是图片。支持的图片格式有：
	 * 
	 * @return
	 */
	public boolean isFile() {
		return fileType != null;
	}

	/**
	 * 获取文件格式
	 * 
	 * @return
	 */
	public String getFileFormat() {
		return this.fileType;
	}

	/**
	 * (non-Javadoc)
	 * 
	 */
	@Override
	public byte[] getFileData() {
		return fileData;
	}

	private String getFileFormat(byte[] contents) {
		if (contents == null) {
			return null;
		}
		for (int i = 0; i < FILE_MAGS.length; i++) {
			byte[] mag = FILE_MAGS[i];
			if (contents.length >= mag.length) {
				if (Arrays.equals(Arrays.copyOf(contents, mag.length), mag)) {
					return FILE_EXTS[i];
				}
			}
		}
		return null;
	}

	/**
	 * (non-Javadoc)
	 * 
	 */
	@SuppressWarnings("restriction")
	@Override
	public String getBase64FileData() {
		if (getFileData() == null) {
			return null;
		}
		sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
		return encoder.encode(getFileData());
	}

}
